package com.igd.interceptors;

import org.apache.log4j.Logger;

import com.igd.common.constant.RequestConstant;
import com.igd.exceptions.IgdException;
import com.igd.pojo.vo.ErrorData;
import com.igd.pojo.vo.ExtData;
import com.igd.utils.CommonUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @createDate 2013-7-19
 *
 * @author QIAOYU
 *
 * @version 1.0
 *
 * @description 错误异常拦截器
 */

public class ExceptionInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -4980981512969515046L;

	private Logger logger = Logger.getLogger(this.getClass());
	
	/** JSON返回的扩展数据对象 */
	private ExtData<Object> extData = new ExtData<Object>();
	
	/** 针对ajax请求进行返回值JSON处理的拦截器 */
	private final String JSON_INTERCEPTOR_NAME = "responseJsonIntercetor";
	
	/** 默认是认为不包含JSON处理拦截器 */
	private boolean hasJsonInterceptor = Boolean.FALSE;
	
	/** 处理之后的返回对象页面 */
	private String resultPage = null;
	
	private final String JSON_RSP_PAGE = "jsonPage";
	
	private final String ERR_RSP_PAGE = "errorPage";

	public String intercept(ActionInvocation invocation){
		
		try {

			extData.setStatusCode(ExtData.FAIL);
			
			invocation.invoke();
			
		}catch(IgdException ie){
			
			extData.setMessage(ie.getMessage());

			logger.error(ie.getMessage());

		}catch (Exception e) {
			
			extData.setMessage(e.getMessage());

			logger.error(e.getMessage());

		}finally{
			
			this.hasJsonInterceptor = CommonUtil.hasIntercetor(invocation, JSON_INTERCEPTOR_NAME);
			
			logger.info(invocation.getProxy().getActionName() + " has " + this.JSON_INTERCEPTOR_NAME + " is:"+this.hasJsonInterceptor);
			
			if(this.hasJsonInterceptor){
				
				invocation.getInvocationContext().put(RequestConstant.EXT_DATA_KEY, extData);
				
				this.resultPage = this.JSON_RSP_PAGE;

			}else{
				
				ErrorData err = new ErrorData();
				
				invocation.getInvocationContext().put(RequestConstant.REQ_ERR_INFO, err);
				
				this.resultPage = this.ERR_RSP_PAGE;

			}
		}
		
		return this.resultPage;
	}
}
